package org.csu.mypetstore.controller;

import com.alibaba.fastjson.JSONObject;
import org.csu.mypetstore.domain.*;
import org.csu.mypetstore.service.CatalogService;
import org.csu.mypetstore.service.LogService;
import org.csu.mypetstore.service.OrderService;
import org.csu.mypetstore.service.SignInService;
import org.csu.mypetstore.util.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

@Controller
@RequestMapping("/account")
public class AccountController {

    @Autowired
    SignInService signInService;

    @Autowired
    Account account;

    @Autowired
    Account account2;

    @Autowired
    HttpSession session;

    @Autowired
    OrderService orderService;

    @Autowired
    Cart cart;

    @Autowired
    CatalogService catalogService;

    @Autowired
    LogService logService;


    @GetMapping("/signon")
    public String signonForm(Model model)
    {
        model.addAttribute("account",account);
        return "account/SignonForm";
    }
    @PostMapping("/signon")
    public String signonSubmit(@ModelAttribute Account account, HttpServletRequest request,Model model)
    {
        //获得输入的验证码值
        String value1=request.getParameter("vCode");
        /*获取图片的值*/
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;
        //转为小写
        value1 = value1.toLowerCase();
        value2 = value2.toLowerCase();
        if(value2.equals(value1)){
            isSame = true;
        }
        if(account.getUsername().equals("manager") && account.getPassword().equals("manager") &&isSame)
        {
            List<Category> categoryList = catalogService.getCategoryList();
            session.setAttribute("categoryList",categoryList);
            return "manage/catalog/ManageCategory";
        }
        // 将用户的明文密码转成MD5加密后的密码

        String password=MD5Utils.md5(request.getParameter("password"));
        this.account = signInService.getAccount(account.getUsername(),password);
        if(this.account!=null&&isSame)
        {
            session.setAttribute("account",this.account);
            session.setAttribute("flag",1);
            List<Order> orderList = orderService.getOrdersByUsername(this.account.getUsername());
            session.setAttribute("orderList",orderList);
            List<CartItem> cartItems = catalogService.getCartItemListByUserName(this.account.getUsername());
            Iterator<CartItem> it = cartItems.iterator ();
            while(it.hasNext()) {
                int i = 0;
                CartItem cartItem = it.next();
                Item item = catalogService.getItem(cartItem.getItemId());
                while(i < cartItem.getQuantity()){
                    cart.addItem(item,true);
                    i++;
                }
            }
            session.setAttribute("cart", cart);
            List<Category> categoryList = catalogService.getCategoryList();
            model.addAttribute("categoryList",categoryList);
            return "catalog/main";
        }
        else {
            if(!isSame) {
                model.addAttribute("msg","验证码错误");
            }
            else {
                //登录失败
                model.addAttribute("msg", "用户名或密码错误");
            }
            return "account/SignonForm";
        }

    }
    @GetMapping("/signoff")
    public String signoffForm(Model model)
    {
        session.setAttribute("account",null);
        session.setAttribute("cart",null);
        session.setAttribute("flag",null);
        List<Category> categoryList = catalogService.getCategoryList();
        model.addAttribute("categoryList",categoryList);
        return "catalog/main";
    }
    @GetMapping("/newAccountForm")
    public String newAccountForm(){
        return "account/NewAccountForm";
    }
    @PostMapping("/newAccount")
    public String newAccount(HttpServletRequest request,HttpSession session,Model model){
        //获得输入的验证码值
        String value1=request.getParameter("vCode");
        /*获取图片的值*/
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;

        //转为小写
        value1 = value1.toLowerCase();
        value2 = value2.toLowerCase();
        System.out.println(value1+"**********************");
        System.out.println(value2+"++++++++++++++++++++++++++++");
        if(value2.equals(value1)){
            isSame = true;
        }
        if(isSame){
            session = request.getSession();
            Account account = (Account) session.getAttribute("account") ;
            String username = request.getParameter("username");
            return "account/newAccount";
        }
        return "account/newAccountForm";
    }

    @PostMapping("/SaveInformation")
    public String SaveInformation(HttpServletRequest req,Model model) {

        //获得输入的验证码值
        String value1=req.getParameter("vCode");
        /*获取图片的值*/
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;

        //转为小写
        value1 = value1.toLowerCase();
        value2 = value2.toLowerCase();
        System.out.println(value1+"**********************");
        System.out.println(value2+"++++++++++++++++++++++++++++");
        if(value2.equals(value1)){
            isSame = true;
        }
        if (isSame) {

            String username = null;
            String password = null;
            String email = null;
            String firstname = null;
            String lastname = null;
            String status = null;
            String address1 = null;
            String address2 = null;
            String city = null;
            String state = null;
            String zip = null;
            String country = null;
            String phone = null;
            String favouriteCategoryId = null;
            String languagePreference = null;

            try {
                req.setCharacterEncoding("UTF-8");
            } catch (Exception e) {

            }

            username = req.getParameter("username");
            password = req.getParameter("password");
            email = req.getParameter("email");
            lastname = req.getParameter("lastName");
            firstname = req.getParameter("firstName");
            status = req.getParameter("status");
            address1 = req.getParameter("address1");
            address2 = req.getParameter("address2");
            city = req.getParameter("city");
            state = req.getParameter("state");
            zip = req.getParameter("zip");
            country = req.getParameter("country");
            phone = req.getParameter("phone");
            languagePreference = req.getParameter("languagePreference");
            favouriteCategoryId = req.getParameter("favouriteCategoryId");
            String listOption = req.getParameter("listOption");
            String bannerOption = req.getParameter("bannerOption");

            // 将密码进行MD5加密
            password= MD5Utils.md5(password);

            account.setUsername(username);
            account.setPassword(password);
            account.setEmail(email);
            account.setFirstName(firstname);
            account.setLastName(lastname);
            account.setStatus(status);
            account.setAddress1(address1);
            account.setAddress2(address2);
            account.setCity(city);
            account.setState(state);
            account.setZip(zip);
            account.setCountry(country);
            account.setPhone(phone);
            account.setFavouriteCategoryId(favouriteCategoryId);
            account.setLanguagePreference(languagePreference);
            account.setListOption(Boolean.parseBoolean(listOption));
            account.setBannerOption(Boolean.parseBoolean(bannerOption));

            signInService.insertAccount(account);
            if (account != null) {
                HttpServletRequest httpRequest = req;
                String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                        + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());


                String logInfo = logService.logInfo(" ") + strBackUrl + " SignIn";
                logService.insertLogInfo(account.getUsername(), logInfo);

            }
            return "catalog/main";
        }
        else{
            model.addAttribute("msg","验证码错误");
            return "account/NewAccountForm";
        }

    }
    @PostMapping("/UpdateInformation")
    public String UpdateInformation(HttpServletRequest req, HttpServletResponse response,Model model) {
        try {
            req.setCharacterEncoding("UTF-8");
        } catch (Exception e) {

        }
        //获得输入的验证码值
        String value1=req.getParameter("vCode");
        /*获取图片的值*/
        String value2=(String)session.getAttribute("checkcode");
        Boolean isSame = false;
        /*对比两个值（字母不区分大小写）*/
        if(value2==null)
        {
            isSame = true;
        }
        else  {
            if (value2.equalsIgnoreCase(value1)) {
                isSame = true;
            }
        }

        account = (Account) session.getAttribute("account");
        String username = account.getUsername();
        String password = req.getParameter("password");
        String repeatedPassword = req.getParameter("repeatedPassword");
        String firstName = req.getParameter("firstname");
        String lastName = req.getParameter("lastname");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address1 = req.getParameter("address1");
        String address2 = req.getParameter("address2");
        String city = req.getParameter("city");
        String state = req.getParameter("state");
        String zip = req.getParameter("zip");
        String country = req.getParameter("country");
        String languagePreference = req.getParameter("languagePreference");
        String favouriteCategoryId = req.getParameter("favouriteCategoryId");
//        String listOption = req.getParameter("listOption");
//        String bannerOption = req.getParameter("bannerOption");
        String a = req.getParameter("listOption");
        boolean listOption =false;
        if(a!=null&&a.equals("1"))
        {
            listOption= true;
        }
        String b = req.getParameter("bannerOption");
        boolean bannerOption = false;
        if(b!=null&&b.equals("1"))
        {
            bannerOption= true;
        }

        if(!isSame)
        {
            model.addAttribute("msg","验证码错误");
            return "account/EditAccountForm";
        }
        else {
            if (password.equals(repeatedPassword)) {
                // 将密码进行MD5加密
                password= MD5Utils.md5(password);
                account.setUsername(username);
                account.setPassword(password);
                account.setFirstName(firstName);
                account.setLastName(lastName);
                account.setEmail(email);
                account.setPhone(phone);
                account.setAddress1(address1);
                account.setAddress2(address2);
                account.setCity(city);
                account.setState(state);
                account.setZip(zip);
                account.setCountry(country);
                account.setLanguagePreference(languagePreference);
                account.setFavouriteCategoryId(favouriteCategoryId);
                account.setListOption(listOption);
                account.setBannerOption(bannerOption);
                signInService.updateAccount(account);
                session.setAttribute("account", account);
                model.addAttribute("msg", "修改个人信息成功");
                if (account != null) {
                    HttpServletRequest httpRequest = req;
                    String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                            + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());

                    String logInfo = logService.logInfo(" ") + strBackUrl + " Return to the edit html";
                    logService.insertLogInfo(account.getUsername(), logInfo);
                }

                return "catalog/main";
            } else {
                model.addAttribute("msg", "两次密码不一致");
                return "account/EditAccountForm";
            }
        }



    }
    @GetMapping("/myaccount")
    public String myaccount(Model model, HttpServletRequest req) {

            return "account/EditAccountForm";
    }
    @RequestMapping("/UsernameIsExist")
    public void UsernameIsExist(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        response.setContentType("text/xml");
        try {
            PrintWriter out = response.getWriter();
            if (signInService.getAccount(username) != null) {
                out.println("<msg>Exist</msg>");
            } else {
                out.println("<msg>NotExist</msg>");
            }
            out.flush();
            out.close();
        } catch (Exception e) {

        }
    }
    @RequestMapping("/verificationCode")
    @GetMapping("/random.jpg")
    private void GetRandom(HttpServletRequest request, HttpServletResponse response) throws IOException {

        response.setContentType("image/jpeg");
        HttpSession session = request.getSession();
        int width = 60;
        int height = 20;

        //设置浏览器不要缓存此图片
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        //创建内存图像并获得图形上下文
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        /*
         * 产生随机验证码
         * 定义验证码的字符表
         */
        String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        char[] rands = new char[4];
        for (int i = 0; i < 4; i++) {
            int rand = (int) (Math.random() * 36);
            rands[i] = chars.charAt(rand);
        }

        /*
         * 产生图像
         * 画背景
         */
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);

        /*
         * 随机产生120个干扰点
         */

        for (int i = 0; i < 120; i++) {
            int x = (int) (Math.random() * width);
            int y = (int) (Math.random() * height);
            int red = (int) (Math.random() * 255);
            int green = (int) (Math.random() * 255);
            int blue = (int) (Math.random() * 255);
            g.setColor(new Color(red, green, blue));
            g.drawOval(x, y, 1, 0);
        }
        g.setColor(Color.BLACK);
        g.setFont(new Font(null, Font.ITALIC | Font.BOLD, 18));

        //在不同高度输出验证码的不同字符
        g.drawString("" + rands[0], 1, 17);
        g.drawString("" + rands[1], 16, 15);
        g.drawString("" + rands[2], 31, 18);
        g.drawString("" + rands[3], 46, 16);
        g.dispose();

        //将图像传到客户端
        ServletOutputStream sos = response.getOutputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "JPEG", baos);
        byte[] buffer = baos.toByteArray();
        response.setContentLength(buffer.length);
        sos.write(buffer);
        baos.close();
        sos.close();

        session.setAttribute("checkcode", new String(rands));
    }
    @GetMapping("usernameIsExist")
    private void usernameIsExist(String username,HttpServletRequest request,HttpServletResponse response) throws IOException {
        account.setUsername(username);

        response.setContentType("text/xml");
        PrintWriter out = response.getWriter();

        if(signInService.getAccount(account.getUsername()) != null){
            out.println("<msg>Exist</msg>");
        }
        else if("".equals(username))
        {
            out.println("<msg>Null</msg>");
        }
        else {
            out.println("<msg>NotExist</msg>");
        }
        out.flush();
        out.close();
    }

    @RequestMapping("/ViewEditInformationFormServlet")
    public String ViewEditInformationFormServlet(HttpServletRequest req, Model model) {
        HttpSession session = req.getSession();
        Account account = (Account) session.getAttribute("account");
        if(account==null){//处理从后台来的account为null的现象
            String username = req.getParameter("username");
            if(username!=null)
                account = signInService.getAccount(username);
            else {
                return "/account/SignonForm";
            }
        }
        String username = account.getUsername();
        if (username == null) {
            return "/account/SignonForm";
        } else {
            model.addAttribute("account", account);
            session.setAttribute("account", account);
            return "account/accountEdit";
        }

    }

    //短信登录
    @GetMapping("/SMSLogin")
    public String SMSLogin(){
        return "account/SMSLogin";
    }
    @GetMapping("/codeSignOn")
    public String SignOnByCode(String code,HttpServletRequest req,Model model){
        JSONObject UserCode = (JSONObject) session.getAttribute("code");
        if(session.getAttribute("code")==null)
        {
            model.addAttribute("msg", "验证码不能为空");
            return "account/SMSLogin";
        }else{
        String TrueCode = UserCode.getString("code");
        String tell = UserCode.getString("memPhone");
            if (code.equals(TrueCode)) {
                account = signInService.getAccount(tell);
                if (account != null) {
                    session.setAttribute("account", this.account);
                    session.setAttribute("flag", 1);
                    List<Order> orderList = orderService.getOrdersByUsername(this.account.getUsername());
                    session.setAttribute("orderList", orderList);
                    List<CartItem> cartItems = catalogService.getCartItemListByUserName(this.account.getUsername());
                    Iterator<CartItem> it = cartItems.iterator();
                    while (it.hasNext()) {
                        int i = 0;
                        CartItem cartItem = it.next();
                        Item item = catalogService.getItem(cartItem.getItemId());
                        while (i < cartItem.getQuantity()) {
                            cart.addItem(item, true);
                            i++;
                        }
                    }
                    session.setAttribute("cart", cart);
                } else {
                    String username = tell;
                    String password = "undefind";
                    String email = "undefind";
                    String firstname = "undefind";
                    String lastname = "undefind";
                    String status = "OK";
                    String address1 = "undefind";
                    String address2 = "undefind";
                    String city = "undefind";
                    String state = "undefind";
                    String zip = "undefind";
                    String country = "undefind";
                    String phone = "undefind";
                    String favouriteCategoryId = "FISH";
                    String languagePreference = "English";
                    String listOption = "true";
                    String bannerOption = "true";

                    // 将密码进行MD5加密
                    password= MD5Utils.md5(password);
                    account2.setUsername(username);
                    account2.setPassword(password);
                    account2.setEmail(email);
                    account2.setFirstName(firstname);
                    account2.setLastName(lastname);
                    account2.setStatus(status);
                    account2.setAddress1(address1);
                    account2.setAddress2(address2);
                    account2.setCity(city);
                    account2.setState(state);
                    account2.setZip(zip);
                    account2.setCountry(country);
                    account2.setPhone(phone);
                    account2.setFavouriteCategoryId(favouriteCategoryId);
                    account2.setLanguagePreference(languagePreference);
                    account2.setListOption(Boolean.parseBoolean(listOption));
                    account2.setBannerOption(Boolean.parseBoolean(bannerOption));

                    signInService.insertAccount(account2);
                    session.setAttribute("account",account2);
                    if (account2 != null) {
                        HttpServletRequest httpRequest = req;
                        String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                                + httpRequest.getContextPath() + httpRequest.getServletPath() + "?" + (httpRequest.getQueryString());


                        String logInfo = logService.logInfo(" ") + strBackUrl + " SignIn";
                        logService.insertLogInfo(account2.getUsername(), logInfo);

                    }
                }
                List<Category> categoryList = catalogService.getCategoryList();
                model.addAttribute("categoryList",categoryList);
                session.setAttribute("flag",1);
                return "catalog/main";
            } else {
                model.addAttribute("msg", "验证码错误");
                return "account/SMSLogin";
            }
        }
    }


}
